package com.zhisland.base.support.common.logger;

import com.zhisland.base.support.common.anotation.EnableLogger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.ReflectionUtils.FieldCallback;

import java.lang.reflect.Field;

/**
 * 自定义声明注入
 * User: wangyanginfo
 * Date: 12-9-5
 * Time: 上午9:35
 */
@Component("loggerInjector")
public class LoggerInjector implements BeanPostProcessor {

    private static Logger logger = LoggerFactory.getLogger(LoggerInjector.class);

    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException {
        return bean;
    }

    public Object postProcessBeforeInitialization(final Object bean, String beanName)
            throws BeansException {
        //logger.info("-- 日志注解初始化开始 --");
        ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() {
            public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
                // make the field accessible if defined private
                ReflectionUtils.makeAccessible(field);
                EnableLogger _enableLogger = field.getAnnotation(EnableLogger.class);
                if (null != _enableLogger) {
                    String _className = bean.getClass().getName();
                     if (_enableLogger.type() == EnableLogger.Type.SLF4J) {
                        Logger _logger = LoggerFactory.getLogger(_className);
                        field.set(bean, _logger);
                    } else if (_enableLogger.type() == EnableLogger.Type.LOG4J) {
                        org.apache.log4j.Logger _logger = org.apache.log4j.Logger.getLogger(_className);
                        field.set(bean, _logger);
                    }
                }
            }
        });
        //logger.info("-- 日志注解初始化完成 --");
        return bean;
    }

}
